package cn.zhz.cloud.auth.web.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.zhz.cloud.auth.web.mapper.IRoleMapper;
import cn.zhz.cloud.auth.web.model.dto.RoleQueryDto;
import cn.zhz.cloud.auth.web.model.dto.RoleSaveDto;
import cn.zhz.cloud.auth.web.model.po.RolePo;
import cn.zhz.cloud.auth.web.model.vo.RoleVo;
import cn.zhz.cloud.auth.web.service.IRoleService;
import cn.zhz.cloud.auth.web.service.IUserRoleService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色 Service实现类
 *
 * @author zhz
 * @since 2022-11-08
 */
@Service
@RequiredArgsConstructor
public class RoleServiceImpl extends ServiceImpl<IRoleMapper, RolePo> implements IRoleService {

    private final IUserRoleService iUserRoleService;

    /**
     * 分页查询
     *
     * @param queryDto 查询参数
     * @return
     */
    @Override
    public Page<RoleVo> page(RoleQueryDto queryDto) {
        long current = queryDto.getCurrent();
        long pageSize = queryDto.getSize();
        Page<RolePo> rolePoPage = baseMapper.selectPage(new Page<>(current, pageSize), Wrappers.lambdaQuery(RolePo.class));
        List<RoleVo> roleVoList = rolePoPage.getRecords().stream().map(rolePo -> BeanUtil.copyProperties(rolePo, RoleVo.class)).collect(Collectors.toList());

        return new Page<RoleVo>(current, pageSize)
                .setTotal(rolePoPage.getTotal())
                .setRecords(roleVoList);
    }

    /**
     * 详情
     *
     * @param id 主键
     * @return
     */
    @Override
    public RoleVo info(Long id) {
        RolePo rolePo = baseMapper.selectById(id);
        if (rolePo == null) {
            // TODO
        }
        return BeanUtil.copyProperties(rolePo, RoleVo.class);
    }

    /**
     * 保存
     *
     * @param saveDto 保存参数
     * @return 主键
     */
    @Override
    public Long save(RoleSaveDto saveDto) {
        RolePo rolePo = BeanUtil.copyProperties(saveDto, RolePo.class);
        this.saveOrUpdate(rolePo);
        return rolePo.getId();
    }

    /**
     * 删除
     *
     * @param id 主键
     */
    @Override
    public void delete(Long id) {
        baseMapper.deleteById(id);
    }

    /**
     * 获取角色编码列表
     *
     * @param userId
     * @return
     */
    @Override
    public List<String> getRoleCodeList(Long userId) {
        return baseMapper.getRoleCodeListByUserId(userId);
    }
}
